package com.weiai.wedding.dao.user;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.weiai.wedding.dao.BaseQueryDao;
import com.weiai.wedding.entity.user.User;
import com.weiai.wedding.util.Pagination;
import com.weiai.wedding.util.StatusConstants;

@Component
public class UserExpDaoImpl implements UserExpDao {
	@PersistenceContext
	private EntityManager em;
	@Autowired
	private BaseQueryDao base;
	@Override
	public Pagination<User> findUserList(User user, Pagination<User> page) {
		CriteriaBuilder builder = em.getCriteriaBuilder();
		CriteriaQuery<User> query = builder.createQuery(User.class);
		Root<User> u = query.from(User.class);
		query.select(u);
		List<Predicate> predicateList = new ArrayList<Predicate>();
		Expression<String> cn = u.get("loginName");
		String loginName = user.getLoginName();
		if (!StringUtils.isBlank(loginName)) {
			predicateList.add(builder.like(cn, "%" + loginName + "%"));
		}
		predicateList.add(builder.notEqual(u.get("status"), StatusConstants.DELETE_STATUS));
		Predicate[] predicates = new Predicate[predicateList.size()];
		predicateList.toArray(predicates);
		query.where(predicates);
		Order desc = builder.asc(u.get("id"));
		query.orderBy(desc);
		Pagination pg = base.getPage(query, page, User.class, predicates);
		return pg;

	}

}
